<template>
  <div class="page">
  <div class="cart-container">
    <!-- 导航栏 -->
    <div class="navbar">
      <div class="navbar-title">购物车</div>
      <div>
        <i class="fas fa-ellipsis-v"></i>
      </div>
    </div>

    <!-- 空购物车界面 -->
    <div v-if="!cartItems.length" class="empty-cart">
      <div class="empty-icon">
        <i class="fas fa-shopping-cart"></i>
      </div>
      <div class="empty-text">您的购物车还是空的</div>
      <router-link to="/" class="btn btn-primary">去逛逛</router-link>
    </div>

    <!-- 购物车有商品时的界面 -->
    <div v-else class="cart-section">
      <div v-for="store in groupedCartItems" :key="store.storeId" class="store-card">
        <div class="store-header">
          <input 
            type="checkbox" 
            class="store-checkbox" 
            :checked="isStoreAllSelected(store)"
            @change="toggleStoreSelection(store)"
          >
          <div class="store-name">{{ store.storeName }}</div>
          <div class="store-coupon" @click="goToStore(store.storeId)">进入</div>
        </div>

        <div v-for="item in store.items" :key="item.cartItemId" class="cart-item">
          <input 
            type="checkbox" 
            class="item-checkbox" 
            :checked="item.selected"
            @change="updateItemSelection(item)"
          >
          <div class="item-content-wrapper" @click="goToProductDetail(item.productId)">
            <img class="item-image" :src="item.mainImage" :alt="item.name">
            <div class="item-content">
              <div class="item-name">{{ item.name }}</div>
              <div class="item-spec">{{ item.specValue || "默认规格" }}</div>
              <div class="item-price-row">
                <div class="item-price">¥{{ item.price }}</div>
                <!-- 商品已下架时显示下架提示 -->
                <div v-if="item.delete === 1" class="out-of-stock-action">
                  <button class="reselect-button off-shelf" @click.stop="handleDeletedProduct(item)">
                    <i class="fas fa-exclamation-circle"></i>
                    商品已下架，请重新选择
                  </button>
                </div>
                <!-- 规格已下架时显示下架提示 -->
                <div v-else-if="item.specDelete === 1" class="out-of-stock-action">
                  <button class="reselect-button spec-off-shelf" @click.stop="handleDeletedSpec(item)">
                    <i class="fas fa-exclamation-circle"></i>
                    商品规格已下架，重新选择规格
                  </button>
                </div>
                <!-- 数量控制器 -->
                <div v-else-if="item.isAmple !== 0" class="quantity-control" @click.stop>
                  <button class="quantity-button" @click.stop="decreaseQuantity(item)">-</button>
                  <input 
                    type="number" 
                    min="1" 
                    class="quantity-input" 
                    v-model.number="item.quantity" 
                    @change="updateQuantity(item)" 
                    @click.stop 
                    @focus.stop 
                    @input.stop
                  >
                  <button class="quantity-button" @click.stop="increaseQuantity(item)">+</button>
                </div>
                <!-- 库存不足时显示提示按钮 -->
                <div v-else class="out-of-stock-action">
                  <button class="reselect-button" @click.stop="reselectProduct(item)">
                    <i class="fas fa-exclamation-circle"></i>
                    库存不足，重新选择
                  </button>
                </div>
              </div>
            </div>
          </div>
          <button class="delete-button" @click="removeFromCart(item)">
            <i class="fas fa-trash"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 推荐商品 - 无论购物车是否为空都显示 -->
    <div class="recommended-section">
      <div class="section-header">
        <div class="section-title">猜你喜欢</div>
        <router-link to="/products" class="section-more">更多 ></router-link>
      </div>
      
      <div v-if="recommendedProducts.length === 0" class="empty-recommend">
        <p>暂无推荐商品</p>
      </div>
      
      <div v-else class="recommended-list">
        <router-link 
          v-for="product in recommendedProducts" 
          :key="product.id"
          :to="'/product/' + product.id" 
          class="recommended-item"
        >
          <img class="recommended-image" :src="product.image" :alt="product.name">
          <div class="recommended-name">{{ product.name }}</div>
          <div class="recommended-price">¥{{ product.price }}</div>
        </router-link>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div v-if="cartItems.length" class="cart-footer">
      <div class="all-checkbox">
        <input 
          type="checkbox" 
          :checked="isAllSelected"
          @change="toggleAllSelection"
        >
        <span class="all-checkbox-label">全选</span>
      </div>
      <div class="cart-total">
        <div>合计: <span class="total-price">¥{{ totalPrice }}</span></div>
        <div class="total-desc">含运费</div>
      </div>
      <router-link 
        :to="selectedCount > 0 ? '/checkout' : '#'" 
        class="checkout-button"
        :class="{ 'disabled-button': selectedCount === 0 }"
        @click.native="saveSelectedItems"
      >
        结算({{ selectedCount }})
      </router-link>
    </div>
  </div>

  <TabBar active-tab="cart" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/network/api'
import TabBar from '@/components/TabBar.vue'
import { showDialog } from 'vant'

interface CartItem {
  cartItemId: number
  productId: number
  productName: string
  productImage: string
  price: number
  quantity: number
  selected: boolean
  storeId: number
  storeName: string
  variant: string
  isAmple?: number // 添加库存充足标识
  delete?: number  // 添加商品是否下架的标识
  specDelete?: number // 添加商品规格是否下架的标识
}

interface RecommendedProduct {
  id: number
  name: string
  image: string
  price: number
}

const cartItems = ref<CartItem[]>([])
const recommendedProducts = ref<RecommendedProduct[]>([])
const router = useRouter()

// 获取购物车数据
const fetchCartItems = async () => {
  try {
    const response = await api.getCartItems()
    // 将后端返回的selected数字转换为布尔值
    if (response.data && Array.isArray(response.data)) {
      cartItems.value = response.data.map(item => ({
        ...item,
        selected: item.selected === 1 // 将后端的1/0转换为true/false
      }))
    } else {
      cartItems.value = []
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error)
    cartItems.value = [] // 出错时设置为空数组
  }
}

// 获取推荐商品
const fetchRecommendedProducts = async () => {
  try {
    const response = await api.recommend();
    if (response.data && Array.isArray(response.data)) {
      recommendedProducts.value = response.data.map(item => ({
        id: item.productId,
        name: item.name,
        image: item.mainImage,
        price: item.price
      }));
    } else {
      recommendedProducts.value = [];
    }
  } catch (error) {
    console.error('获取推荐商品失败:', error);
    recommendedProducts.value = [];
  }
}

// 按商店分组购物车商品
const groupedCartItems = computed(() => {
  const groups = new Map()
  cartItems.value.forEach(item => {
    if (!groups.has(item.storeId)) {
      groups.set(item.storeId, {
        storeId: item.storeId,
        storeName: item.storeName,
        items: []
      })
    }
    groups.get(item.storeId).items.push(item)
  })
  return Array.from(groups.values())
})

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + item.price * item.quantity, 0)
})

// 选中的商品
const selectedItems = computed(() => {
  return cartItems.value.filter(item => item.selected)
})

// 是否全选
const isAllSelected = computed(() => {
  return cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
})

// 默认选中的商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length
})

// 商店是否全选
const isStoreAllSelected = (store: any) => {
  return store.items.every((item: CartItem) => item.selected)
}

// 更新商品选中状态
const updateItemSelection = async (item: CartItem) => {
  try {
    const newSelectedStatus = !item.selected
    // 向后端传递1或0数字
    await api.updateCartItemSelection(item.cartItemId, newSelectedStatus ? 1 : 0)
    item.selected = newSelectedStatus
  } catch (error) {
    console.error('更新商品选中状态失败:', error)
  }
}

// 切换全选状态
const toggleAllSelection = async () => {
  const newStatus = !isAllSelected.value
  try {
    await Promise.all(
      cartItems.value.map(item => 
        // 向后端传递1或0数字
        api.updateCartItemSelection(item.cartItemId, newStatus ? 1 : 0)
      )
    )
    cartItems.value.forEach(item => item.selected = newStatus)
  } catch (error) {
    console.error('更新全选状态失败:', error)
  }
}

// 切换商店选中状态
const toggleStoreSelection = async (store: any) => {
  const newStatus = !isStoreAllSelected(store)
  try {
    await Promise.all(
      store.items.map((item: CartItem) => 
        // 向后端传递1或0数字
        api.updateCartItemSelection(item.cartItemId, newStatus ? 1 : 0)
      )
    )
    store.items.forEach((item: CartItem) => item.selected = newStatus)
  } catch (error) {
    console.error('更新商店选中状态失败:', error)
  }
}

// 增加商品数量
const increaseQuantity = async (item: CartItem) => {
  try {
    const response = await api.addProductQuantity(item.cartItemId)

    // 检查是否返回库存不足
    if (response && response.data === "库存不足") {
      showDialog({
        title: '库存提示',
        message: '该商品库存不足，无法继续增加数量',
      })
      return
    }

    item.quantity++
  } catch (error: any) {
    console.error('增加商品数量失败:', error)

    // 检查错误响应是否包含库存不足信息
    if (error.response && error.response.data && error.response.data.data === "库存不足") {
      showDialog({
        title: '库存提示',
        message: '该商品库存不足，无法继续增加数量',
      })
    }
  }
}

// 减少商品数量
const decreaseQuantity = async (item: CartItem) => {
  if (item.quantity > 1) {
    try {
      await api.disProductQuantity(item.cartItemId)
      item.quantity--
    } catch (error) {
      console.error('减少商品数量失败:', error)
    }
  }
}

// 从购物车中移除商品
const removeFromCart = async (item: CartItem) => {
  try {
    await api.removeFromCart(item.cartItemId)
    cartItems.value = cartItems.value.filter(i => i.cartItemId !== item.cartItemId)
  } catch (error) {
    console.error('从购物车中移除商品失败:', error)
  }
}

// 跳转到商品详情页面
const goToProductDetail = (productId: number) => {
  router.push(`/product/${productId}`)
}

// 跳转到店铺详情页面
const goToStore = (storeId: number) => {
  router.push(`/store/${storeId}`)
}

// 处理库存不足商品重新选择
const reselectProduct = async (item: CartItem) => {
  try {
    // 首先从购物车中移除该商品
    await api.removeFromCart(item.cartItemId)
    
    // 显示提示信息
    showDialog({
      title: '商品库存不足',
      message: '该商品已从购物车中移除，将为您跳转至商品详情页',
      confirmButtonText: '确定'
    }).then(() => {
      // 跳转到对应商品的详情页
      router.push(`/product/${item.productId}`)
    })
    
    // 从本地购物车列表中移除该商品
    cartItems.value = cartItems.value.filter(i => i.cartItemId !== item.cartItemId)
  } catch (error) {
    console.error('处理库存不足商品失败:', error)
    
    // 如果出错，仍然尝试跳转到商品详情页
    router.push(`/product/${item.productId}`)
  }
}

// 处理已下架商品
const handleDeletedProduct = async (item: CartItem) => {
  try {
    // 从购物车中移除该商品
    await api.removeFromCart(item.cartItemId)
    
    // 显示提示信息
    showDialog({
      title: '商品已下架',
      message: '该商品已下架并从购物车中移除，请选择其他商品',
      confirmButtonText: '确定'
    }).then(() => {
      // 跳转到首页或商品列表页
      router.push('/products')
    })
    
    // 从本地购物车列表中移除该商品
    cartItems.value = cartItems.value.filter(i => i.cartItemId !== item.cartItemId)
  } catch (error) {
    console.error('处理下架商品失败:', error)
    
    // 如果出错，仍然尝试跳转到商品列表页
    router.push('/products')
  }
}

// 处理已下架规格
const handleDeletedSpec = async (item: CartItem) => {
  try {
    // 从购物车中移除该商品
    await api.removeFromCart(item.cartItemId)
    
    // 显示提示信息
    showDialog({
      title: '规格已下架',
      message: '该商品规格已下架并从购物车中移除，将为您跳转至商品详情页重新选择规格',
      confirmButtonText: '确定'
    }).then(() => {
      // 跳转到商品详情页
      router.push(`/product/${item.productId}`)
    })
    
    // 从本地购物车列表中移除该商品
    cartItems.value = cartItems.value.filter(i => i.cartItemId !== item.cartItemId)
  } catch (error) {
    console.error('处理下架规格失败:', error)
    
    // 如果出错，仍然尝试跳转到商品详情页
    router.push(`/product/${item.productId}`)
  }
}

// 保存选中的商品到本地存储
const saveSelectedItems = (e: Event) => {
  if (selectedItems.value.length > 0) {
    // 只保存cartItemId而不是整个商品对象，避免超出localStorage配额
    const selectedIds = selectedItems.value.map(item => ({
      cartItemId: item.cartItemId,
      productId: item.productId,
      quantity: item.quantity
    }))
    localStorage.setItem('selected_cart_items', JSON.stringify(selectedIds))
    console.log('已保存', selectedItems.value.length, '个选中商品到本地存储')

    // 清除可能存在的checkout会话标记，确保下次进入结算页面时能正确加载
    sessionStorage.removeItem('checkout_session_active')
  } else {
    // 如果没有选中商品，阻止导航并提示用户
    if(e) {
      e.preventDefault()
    }
    showDialog({
      title: '提示',
      message: '请至少选择一个商品'
    })
  }
}

// 在用户点击router-link前保存选中商品数据
// 由于Vue 3的限制，我们不能使用beforeEach直接在setup中注册
// 使用watch来监听选中商品的变化，实时保存到本地存储
watch(selectedItems, (newItems) => {
  if (newItems.length > 0) {
    // 只保存cartItemId而不是整个商品对象，避免超出localStorage配额
    const selectedIds = newItems.map(item => ({
      cartItemId: item.cartItemId,
      productId: item.productId,
      quantity: item.quantity
    }))
    localStorage.setItem('selected_cart_items', JSON.stringify(selectedIds))
    console.log('已实时保存', newItems.length, '个选中商品到本地存储')
  } else {
    localStorage.removeItem('selected_cart_items')
  }
})

// 更新商品数量（通过直接输入）
const updateQuantity = async (item: CartItem) => {
  // 确保数量至少为1
  if (item.quantity < 1) {
    item.quantity = 1;
  }
  
  // 将数量四舍五入为整数
  item.quantity = Math.round(item.quantity);
  
  try {
    // 调用更新数量的API
    const response = await api.updateCartItemQuantity(item.cartItemId, item.quantity);
    
    // 检查返回结果
    if (response && response.data === "库存不足") {
      showDialog({
        title: '库存提示',
        message: '该商品库存不足，请减少购买数量',
      });
      
      // 重新获取购物车数据，确保显示正确的数量
      fetchCartItems();
      return;
    }
  } catch (error: any) {
    console.error('更新商品数量失败:', error);
    
    // 检查错误响应是否包含库存不足信息
    if (error.response && error.response.data && error.response.data.data === "库存不足") {
      showDialog({
        title: '库存提示',
        message: '该商品库存不足，请减少购买数量',
      });
      
      // 重新获取购物车数据
      fetchCartItems();
    }
  }
}

onMounted(() => {
  fetchCartItems();
  fetchRecommendedProducts();
})
</script>

<style scoped>
.cart-container {
  min-height: 100vh;
  background-color: #f8fafc;
  padding-bottom: 60px;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background-color: white;
  border-bottom: 1px solid #e2e8f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-back {
  color: #4a5568;
  text-decoration: none;
  font-size: 18px;
  padding: 5px;
}

.navbar-title {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  flex: 1;
  text-align: center;
}

.navbar-title + div {
  width: 30px;
  text-align: right;
}

.navbar-title + div i {
  color: #4a5568;
  font-size: 18px;
  padding: 5px;
  cursor: pointer;
}

.empty-cart {
  padding: 40px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 60px;
  color: #cbd5e0;
  margin-bottom: 20px;
}

.empty-text {
  color: #718096;
  margin-bottom: 20px;
  font-size: 16px;
}

.btn.btn-primary {
  display: inline-block;
  background-color: #3490dc;
  color: white;
  padding: 10px 20px;
  border-radius: 20px;
  text-decoration: none;
  margin-bottom: 30px;
}

.store-card {
  background-color: white;
  margin-bottom: 10px;
}

.store-header {
  display: flex;
  padding: 15px;
  align-items: center;
  border-bottom: 1px solid #e2e8f0;
}

.store-checkbox {
  margin-right: 10px;
}

.store-name {
  flex: 1;
  font-weight: 500;
  font-size: 15px;
}

.store-coupon {
  font-size: 12px;
  padding: 2px 8px;
  background-color: #ebf4ff;
  color: #3490dc;
  border-radius: 10px;
}

.cart-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #e2e8f0;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-checkbox {
  margin-right: 10px;
  align-self: center;
}

.item-content-wrapper {
  flex: 1;
  display: flex;
  cursor: pointer;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 5px;
  object-fit: cover;
  margin-right: 10px;
}

.item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.item-name {
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 5px;
}

.item-spec {
  font-size: 12px;
  color: #718096;
  margin-bottom: 5px;
  padding: 2px 5px;
  background-color: #f1f5f9;
  border-radius: 3px;
  display: inline-block;
}

.item-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.item-price {
  color: #e53e3e;
  font-weight: bold;
  font-size: 16px;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
}

.quantity-button {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f7fafc;
  color: #718096;
  border: none;
  cursor: pointer;
}

.quantity-input {
  width: 40px;
  height: 30px;
  text-align: center;
  border: none;
  border-left: 1px solid #e2e8f0;
  border-right: 1px solid #e2e8f0;
  -moz-appearance: textfield; /* Firefox */
}

/* 移除Chrome、Safari、Edge、Opera的默认样式 */
.quantity-input::-webkit-outer-spin-button,
.quantity-input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.recommended-section {
  background-color: white;
  padding: 15px;
  margin-top: 10px;
  border-radius: 8px;
}

/* 购物车为空时的样式调整 */
.empty-cart + .recommended-section {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.section-more {
  font-size: 14px;
  color: #3490dc;
  text-decoration: none;
}

.recommended-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 12px;
  padding-bottom: 5px;
}

.recommended-item {
  text-decoration: none;
  color: inherit;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.2s;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
}

.recommended-item:hover {
  transform: translateY(-3px);
}

.recommended-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 8px 8px 0 0;
}

.recommended-name {
  font-size: 14px;
  margin: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 40px;
  line-height: 1.4;
}

.recommended-price {
  color: #e53e3e;
  font-size: 16px;
  font-weight: 600;
  margin: 0 8px 8px 8px;
}

.empty-recommend {
  text-align: center;
  padding: 20px;
  color: #718096;
  font-size: 14px;
}

.cart-footer {
  position: fixed;
  bottom: 60px;
  left: 0;
  right: 0;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 10px 15px;
  box-shadow: 0 -1px 5px rgba(0,0,0,0.05);
}

.all-checkbox {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.all-checkbox-label {
  font-size: 14px;
  margin-left: 5px;
}

.cart-total {
  flex: 1;
  text-align: right;
  padding-right: 15px;
}

.total-price {
  color: #e53e3e;
  font-weight: bold;
  font-size: 18px;
}

.total-desc {
  font-size: 12px;
  color: #718096;
}

.checkout-button {
  background-color: #e53e3e;
  color: white;
  padding: 8px 25px;
  border-radius: 20px;
  font-weight: 500;
  text-decoration: none;
}

.disabled-button {
  background-color: #cbd5e0;
  cursor: not-allowed;
}

.delete-button {
  background: none;
  border: none;
  padding: 8px;
  cursor: pointer;
  margin-left: 10px;
  color: #e53e3e;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.delete-button:hover {
  background-color: #fed7d7;
}

/* 添加库存不足样式 */
.out-of-stock-action {
  display: flex;
  align-items: center;
}

.reselect-button {
  background-color: #fef2f2;
  color: #e53e3e;
  border: 1px solid #fee2e2;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
}

.reselect-button:hover {
  background-color: #fee2e2;
}

.reselect-button i {
  margin-right: 4px;
  font-size: 14px;
}

.reselect-button.off-shelf {
  background-color: #fef2f2;
  border-color: #fecaca;
  color: #dc2626;
}

.reselect-button.spec-off-shelf {
  background-color: #fff7ed;
  border-color: #fed7aa;
  color: #ea580c;
}
</style>
